import random

class Address:
    def __init__(self, country, province, street, door_number):
        self.country = country
        self.province = province
        self.street = street
        self.door_number = door_number

class User:
    def __init__(self, id, name, password, address, balance, bank_name):
        self.id = id
        self.name = name
        self.password = password
        self.address = address
        self.balance = balance
        self.bank_name = bank_name

class Bank:
    def __init__(self, bank_name):
        self.users = {}
        self.bank_name = bank_name

    def add_user(self, user):
        if len(self.users) >= 100:
            return 3
        if user.id in self.users:
            return 2
        self.users[user.id] = user
        return 1

    def save(self, id, money):
        if id not in self.users:
            return False
        self.users[id].balance += money
        return True

    def withdraw(self, id, password, money):
        if id not in self.users:
            return 1
        user = self.users[id]
        if user.password != password:
            return 2
        if user.balance < money:
            return 3
        user.balance -= money
        return 0

    def transfer(self, from_id, to_id, password, money):
        if from_id not in self.users or to_id not in self.users:
            return 1
        from_user = self.users[from_id]
        if from_user.password != password:
            return 2
        if from_user.balance < money:
            return 3
        from_user.balance -= money
        self.users[to_id].balance += money
        return 0

    def query(self, id, password):
        if id not in self.users:
            return None, "账号不存在"
        user = self.users[id]
        if user.password != password:
            return None, "密码错误"
        return user, None

def generate_id():
    return str(random.randint(10000000, 99999999))

def handle_open_user(bank):
    if len(bank.users) >= 100:
        print("用户库已满，无法开户。")
        return
    id = None
    for _ in range(1000):
        id = generate_id()
        if id not in bank.users:
            break
    else:
        print("生成账号失败，请稍后再试。")
        return
    name = input("请输入姓名：")
    while True:
        password = input("请输入6位数字密码：")
        if len(password) != 6 or not password.isdigit():
            print("密码必须是6位数字。")
        else:
            password = int(password)
            break
    country = input("请输入国家：")
    province = input("请输入省份：")
    street = input("请输入街道：")
    door_number = input("请输入门牌号：")
    address = Address(country, province, street, door_number)
    while True:
        balance = input("请输入初始存款金额（非负整数）：")
        try:
            balance = int(balance)
            if balance < 0:
                print("金额不能为负数。")
            else:
                break
        except:
            print("请输入有效的整数。")
    user = User(id, name, password, address, balance, bank.bank_name)
    result = bank.add_user(user)
    if result == 1:
        print(f"开户成功！您的账号是：{id}")
    elif result == 2:
        print("发生错误，账号已存在。")
    elif result == 3:
        print("用户库已满，无法开户。")

def handle_save(bank):
    id = input("请输入账号：")
    while True:
        money = input("请输入存款金额（正整数）：")
        try:
            money = int(money)
            if money <= 0:
                print("金额必须大于0。")
            else:
                break
        except:
            print("请输入有效的整数。")
    success = bank.save(id, money)
    if success:
        print("存款成功。")
    else:
        print("账号不存在，存款失败。")

def handle_withdraw(bank):
    id = input("请输入账号：")
    while True:
        password = input("请输入6位数字密码：")
        if len(password) != 6 or not password.isdigit():
            print("密码必须是6位数字。")
        else:
            password = int(password)
            break
    while True:
        money = input("请输入取款金额（正整数）：")
        try:
            money = int(money)
            if money <= 0:
                print("金额必须大于0。")
            else:
                break
        except:
            print("请输入有效的整数。")
    result = bank.withdraw(id, password, money)
    if result == 0:
        print("取款成功。")
    elif result == 1:
        print("账号不存在。")
    elif result == 2:
        print("密码错误。")
    elif result == 3:
        print("余额不足。")

def handle_transfer(bank):

    while True:
        from_id = input("请输入转出账号：")
        if len(from_id) != 8 or not from_id.isdigit():
            print("账号必须是8位数字。")
        else:
            from_id = str(from_id)
            break
    while True:
        to_id = input("请输入转入账号：")
        if len(to_id) != 8 or not to_id.isdigit():
            print("账号必须是8位数字。")
        else:
            to_id = str(to_id)
            break
    while True:
        password = input("请输入转出账号的6位数字密码：")
        if len(password) != 6 or not password.isdigit():
            print("密码必须是6位数字。")
        else:
            password = int(password)
            break
    while True:
        money = input("请输入转账金额（正整数）：")

        try:
            money = int(money)
            if money <= 0:
                print("金额必须大于0。")
            else:
                break
        except:
            print("请输入有效的整数。")
    result = bank.transfer(from_id, to_id, password, money)
    if result == 0:
        print("转账成功。")
    elif result == 1:
        print("账号不存在。")
    elif result == 2:
        print("密码错误。")
    elif result == 3:
        print("余额不足。")

def handle_query(bank):
    id = input("请输入账号：")
    while True:
        password = input("请输入6位数字密码：")
        if len(password) != 6 or not password.isdigit():
            print("密码必须是6位数字。")
        else:
            password = int(password)
            break
    user, error = bank.query(id, password)
    if error:
        print(error)
    else:
        print("\n当前账户信息：")
        print(f"账号: {user.id}")
        print(f"密码: {user.password:06d}")  # 保持6位显示
        print(f"余额: {user.balance}元")
        addr = user.address
        print(f"居住地址: {addr.country}{addr.province}{addr.street}{addr.door_number}")
        print(f"开户行: {user.bank_name}\n")

def main():
    bank = Bank("中国工商银行昌平支行")
    border = '*' * 40
    header = ['中国工商银行', '账户管理系统', 'V1.0']
    menu_items = [
        '1.开户',
        '2.存钱',
        '3.取钱',
        '4.转账',
        '5.查询',
        '6.Bye!'
    ]

    # 打印顶部边框
    print(f'\033[94m{border}\033[0m')

    # 打印标题（带星号装饰）
    for line in header:
        padded_line = f'* {line.center(32)} *'
        print(f'\033[94m{padded_line}\033[0m')

    while True:
        # 打印菜单顶部边框
        print(f'\033[94m{border}\033[0m\n')
        # 打印菜单项
        for item in menu_items:
            padded_item = f'* {item.ljust(34)} *'
            print(f'\033[94m{padded_item}\033[0m')
        # 打印底部边框
        print(f'\033[94m{border}\033[0m')

        choice = input("请选择操作(1-6): ").strip()
        if choice == '1':
            handle_open_user(bank)
        elif choice == '2':
            handle_save(bank)
        elif choice == '3':
            handle_withdraw(bank)
        elif choice == '4':
            handle_transfer(bank)
        elif choice == '5':
            handle_query(bank)
        elif choice == '6':
            print("感谢使用，再见！")
            break
        else:
            print("输入无效，请重新选择！")

if __name__ == "__main__":
    main()